package com.heima.user.service.impl;

import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private CacheService cacheService;
    /**
     * 用户关注/取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.检查参数
        if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();  //用户id
        Integer authorId = dto.getAuthorId();   //作者id
        //用户关注作者
        if (dto.getOperation()==0){
            //将作者写入用户的关注中
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION+userId,authorId.toString(),System.currentTimeMillis());
            //将用户写入作者的粉丝中
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION+authorId,userId.toString(),System.currentTimeMillis());
        }else { //取消关注
            //将作者从用户关注中删除
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION+userId,authorId.toString());
            //将用户从作者粉丝中删除
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION+authorId,userId.toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
